<template>
    <!--图片容器-->
    <div class="image-container" @mouseleave="hideZoomBox" @mousemove="moveZoomBox">
        <!-- 原始图片 -->
        <img :src="url" alt="Product Image" ref="productImage"/>
        <!-- 放大框 -->
        <div v-show="isZoomBoxVisible" ref='mark' class="zoom-box" :style="zoomBoxStyle"></div>
    </div>
    <!-- 放大后的图片容器 -->
    <div class="zoomed-image" ref="big" v-show="isZoomBoxVisible">
        <!-- 放大后的图片 -->
        <img :src="url" alt="Product Image" :style="bigImageStyle"/>
    </div>
</template>

<script setup>
import {ref, defineProps} from 'vue'

const isZoomBoxVisible = ref(true);
const props = defineProps(['url'])
const zoomBoxStyle = ref({
    width: '300px',
    height: '300px',
});

const hideZoomBox = () => {
    isZoomBoxVisible.value = false;
};

const big = ref('')
const productImage = ref('')
const mark = ref('')
const bigImageStyle = ref({})
const moveZoomBox = (event) => {
    isZoomBoxVisible.value = true
    if (isZoomBoxVisible.value) {
        // 获取图片容器的位置信息
        const rect = productImage.value.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;
        // 限制小框的移动范围
        const left = Math.min(Math.max(x - 150, 0), productImage.value.offsetWidth - 300);
        const top = Math.min(Math.max(y - 150, 0), productImage.value.offsetHeight - 300);
        // 计算放大图片的偏移
        const zoomX = -left * (big.value.offsetWidth / mark.value.offsetWidth)
        const zoomY = -top * (big.value.offsetHeight / mark.value.offsetHeight)
        // 更新小框和放大图片的样式
        zoomBoxStyle.value = {
            ...zoomBoxStyle.value,
            top: `${top}px`, // 调整小框位置
            left: `${left}px`
        }
        bigImageStyle.value = {
            left: `${zoomX}px`,
            top: `${zoomY}px`,
        };
    }
};
</script>

<style>
.image-container {
    position: relative;
    border: 1px solid rgba(128, 128, 128, 0.57);
    overflow: hidden;
    height: 100%;
}

.image-container img {
    width: 500px;
    height: 500px;
    object-fit: cover;
}

.zoom-box {
    position: absolute;
    background: rgba(255, 255, 153, 0.6);
    z-index: 1;
    cursor: move;
}

.zoomed-image {
    position: absolute;
    left: 500px;
    top: 0;
    width: 600px; /* 调整放大版本的大小 */
    height: 600px;
    border: 2px solid rgba(128, 128, 128, 0.33);
    display: block;
    overflow: hidden;
    margin-left: 20px;
}

.zoomed-image img {
    width: 1000px;
    height: 1000px;
    position: absolute;
    z-index: 5;
}
</style>
